package com.longkier.gx_library_springboot.Controller;

import com.longkier.gx_library_springboot.Service.AreaService;
import com.longkier.gx_library_springboot.entity.LibraryArea;
import com.longkier.gx_library_springboot.utils.RequestUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
@RequestMapping("/Area")
public class AreaController {

    private final AreaService areaService;

    // 获取所有图书馆区域
    @GetMapping("/all")
    public Map<String, Object> getAllLibraryAreas() {
        try {
            List<LibraryArea> libraryAreas = areaService.getAllLibraryAreas();
            return RequestUtils.buildResponse(libraryAreas, 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("获取图书馆区域时发生异常", 500);
        }
    }

    // 根据ID获取图书馆区域
    @GetMapping("/{id}")
    public Map<String, Object> getLibraryAreaById(@PathVariable Long id) {
        try {
            return areaService.getLibraryAreaById(id)
                    .map(libraryArea -> RequestUtils.buildResponse(libraryArea, 200))
                    .orElse(RequestUtils.buildResponse("图书馆区域不存在", 404));
        } catch (Exception e) {
            return RequestUtils.buildResponse("获取图书馆区域时发生异常", 500);
        }
    }

    // 保存新图书馆区域
    @PostMapping("/save")
    public Map<String, Object> saveLibraryArea(@RequestBody LibraryArea libraryArea) {
        try {
            LibraryArea savedLibraryArea = areaService.saveOrUpdateLibraryArea(libraryArea);
            return RequestUtils.buildResponse(savedLibraryArea, 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("保存图书馆区域时发生异常", 500);
        }
    }

    // 更新图书馆区域
    @PutMapping("/update/{id}")
    public Map<String, Object> updateLibraryArea(@PathVariable Long id, @RequestBody LibraryArea libraryArea) {
        try {
            libraryArea.setAreaCodeId(id);
            LibraryArea updatedLibraryArea = areaService.saveOrUpdateLibraryArea(libraryArea);
            return RequestUtils.buildResponse(updatedLibraryArea, 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("更新图书馆区域时发生异常", 500);
        }
    }

    // 删除图书馆区域
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteLibraryArea(@PathVariable Long id) {
        areaService.deleteLibraryArea(id);
        return RequestUtils.buildResponse("图书馆区域删除成功", 200);
    }
}
